package com.dgut.smart_house.controller;

import com.dgut.smart_house.enums.ResultCode;
import com.dgut.smart_house.service.ControlService;
import com.dgut.smart_house.service.DeviceListService;
import com.dgut.smart_house.util.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/control/api")
public class ControlApiController {

    @Autowired
    DeviceListService deviceListService;
    @Autowired
    ControlService controlService;

    /**
     * 打开设备
     * @param session
     * @param devId
     * @return
     */
    @RequestMapping("/open")
    public RestResult openDevice(HttpSession session,
                                 @RequestParam("devId") int devId){
        if ((int) session.getAttribute("IdFromUserTable") != deviceListService.findUserByDevId(devId)) {
            return new RestResult(ResultCode.NO_AUTH_FAIL, devId);
        }else {
            controlService.openDevice(devId);
            log.info("用户-{}-点击开启设备dev_id={}",session.getAttribute("userId"),devId);
            return new RestResult(ResultCode.SUCCESS.getCode(),"设备已打开",null);
        }
    };

    /**
     * 关闭设备
     * @param session
     * @param devId
     * @return
     */
    @RequestMapping("/close")
    public RestResult closeDevice(HttpSession session,
                                  @RequestParam("devId") int devId){
        if ((int) session.getAttribute("IdFromUserTable") != deviceListService.findUserByDevId(devId)) {
            return new RestResult(ResultCode.NO_AUTH_FAIL, devId);
        }else {
            controlService.closeDevice(devId);
            log.info("用户-{}-点击关闭设备dev_id={}",session.getAttribute("userId"),devId);
            return new RestResult(ResultCode.SUCCESS.getCode(),"设备已关闭",null);
        }
    };
}
